package com.cbw.mvc;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 *所有请求都走DispatchServlet
 */
public class DispatchServlet extends HttpServlet {
    //服务器启动后，该DispatchServlet就会被加载，执行init，加载配置文件到properties对象中
    @Override
    public void init(ServletConfig config) throws ServletException {
        //加载配置文件
        String path = config.getInitParameter("contentConfigLocation");//获取配置文件的名称(路径)
        InputStream is = DispatchServlet.class.getClassLoader().getResourceAsStream(path);//获取配置文件的输入流
        HandlerMapping.load(is);//加载配置文件输入流
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();//1.获取用户的请求uri  /xxx.do
        System.out.println("请求地址:"+uri);
        HandlerMapping.MVCMapping mvcMapping = HandlerMapping.get(uri); //2.获取映射地址池中的映射对象
        if(mvcMapping==null){
            resp.sendError(404,"自定义MVC:映射地址不存在"+uri);
            return;
        }
        Object obj = mvcMapping.getObj(); //3.获取映射对象中的对象，请求的方法，方法返回类型
        Method method = mvcMapping.getMethod();
        Object result=null;
        try {
            result = method.invoke(obj, req, resp);//执行用户请求的方法,要求被执行的方法带参数req,resp
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        switch (mvcMapping.getType()){
            case TEXT:
                resp.getWriter().write((String)result);//向前台响应结果是字符串类型
                break;
            case VIEW:
                resp.sendRedirect((String)result);//向前台响应的结果是一个页面
                break;
        }
    }
}
